import React, { useEffect, useState } from 'react'
// import { Button, message, Space, Spin, Table, Modal } from 'antd'
import { Button, message, Space, Spin, Table } from 'antd'
import dayjs from 'dayjs'
import http from '@/utils/request'
import Filter from '@/components/filter'
import RoleDrawer from './roleDrawer'
import type { roleType } from '@/types'
import { authority } from '@/assets/dict/authCode'
// import { ExclamationCircleFilled } from '@ant-design/icons'

const RoleList: React.FC = () => {
  const [dataSource, setDataSource] = useState<roleType[]>([])
  const [currentRole, setCurrentRole] = useState<roleType>()
  const [isDrawerOpen, setIsDrawerOpen] = useState(false)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [pageConfig, setPageConfig] = useState({
    pageSize: 10,
    pageNum: 1,
    current: 1,
    roleName: '',
    status: ''
  })
  const [loadFlag, setLoadFlag] = useState<number>(new Date().getTime())

  const editRole = (row: roleType) => {
    setCurrentRole(row)
    setIsDrawerOpen(true)
  }

  const addRole = () => {
    setCurrentRole({})
    setIsDrawerOpen(true)
  }

  const initTable = () => {
    setPageConfig((config) => ({
      ...config,
      pageNum: 1
    }))
    setLoadFlag(new Date().getTime())
  }

  const queryRoleList = () => {
    setLoading(true)
    const { pageNum, pageSize, roleName, status } = pageConfig
    http.post('/disp/sys/role/page', {
      pageNum,
      pageSize,
      roleName,
      status
    }).then(res => {
      setTotal(res.data.total || 0)
      setDataSource((res.data.list || []).map((item: { permissionCode: string }) => {
        return {
          ...item,
          permissionCode: item.permissionCode?.split(',')
        }
      }))
    }).finally(() => {
      setLoading(false)
    })
  }

  useEffect(() => {
    queryRoleList()
  }, [loadFlag])

  const pageChange = (pageNum: number, pageSize: number) => {
    pageConfig.pageSize = pageSize
    pageConfig.pageNum = pageNum
    pageConfig.current = pageNum
    queryRoleList()
  }

  const filterOptions = [{
    type: 'input',
    key: 'roleName',
    label: '角色名称'
  }, {
    type: 'select',
    key: 'status',
    label: '角色状态',
    options: [{
      label: '启用',
      value: 'Enable'
    }, {
      label: '停用',
      value: 'Disabled'
    }]
  }]

  const filterChange = (val: any, key: string) => {
    setPageConfig((config) => ({
      ...config,
      pageNum: 1,
      current: 1,
      [key]: val
    }))
  }

  interface columnType {
    title: string;
    dataIndex?: string;
    key: string;
    render?: any
  }

  const columns: columnType[] = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark'
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      key: 'createUserName'
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (_: any, record: any) => (
        <p>{dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')}</p>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, row: any) => (
        <Space size="middle">
          {authority('role-list-edit', <Button size="small" type="link" onClick={() => editRole(row)}>编辑</Button>)}
          {
            row.status === 'Enable' ?
              authority('role-list-switch', <Button onClick={() => handleStatusChange(row, 'disable')} size="small" type="link">停用</Button>):
              authority('role-list-switch', <Button onClick={() => handleStatusChange(row, 'enable')} size="small" type="link">启用</Button>)
          }
        </Space>
      )
    }
  ]

  // const handleDelete = (row: roleType) => {
  //   console.log(row)
  //   const { confirm } = Modal
  //   confirm({
  //     title: '是否删除所选项？',
  //     icon: <ExclamationCircleFilled />,
  //     content: '删除后无法恢复，请谨慎操作',
  //     onOk() {
  //       console.log(row)
  //     },
  //     onCancel() {
  //       console.log('Cancel')
  //     }
  //   })
  // }

  const handleStatusChange = (row: roleType, type: string) => {
    setLoading(true)
    http.post(`/disp/sys/role/${type}`, {
      id: row?.id
    }).then(() => {
      message.success('操作成功')
    }).catch(err => {
      message.error(err.msg || '操作失败')
    }).finally(() => {
      initTable()
      setLoading(false)
    })
  }

  const handleClose = (refresh: boolean) => {
    setIsDrawerOpen(false)
    if (refresh) {
      initTable()
    }
  }
  return (
    <Spin spinning={loading}>
      <Filter items={filterOptions} onChange={filterChange} onSure={queryRoleList}/>
      <div className="flex-row" style={{ width: '100%' }}>
        <div className="flex1"/>
        {authority('role-list-add', <Button onClick={addRole}>添加</Button>)}
      </div>
      <Table
        pagination={{ 
          position: ['bottomRight'], 
          ...pageConfig, 
          total, 
          onChange: pageChange, 
          showTotal: (total) => `共 ${total} 条`,
          pageSizeOptions: ['10', '20', '30', '50'],
          showSizeChanger: true
        }}
        dataSource={dataSource}
        columns={columns}
        rowKey="id" />
      <RoleDrawer isOpen={isDrawerOpen} role={currentRole} onClose={handleClose} />
    </Spin>
  )
}
export default RoleList